<?php

namespace App\Http\Controllers\AdminMobile;

use App\Http\Controllers\ZipFileDownloadController;
use App\Models\Reservation;
use App\Models\ReservationApply;
use App\Models\ReservationSchedule;
use App\Models\ReservationSeat;
use App\Validate\ReservationValidate;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 文化配送类 座位预约管理
 */
class ReservationSeatController extends CommonController
{
    protected $model;
    protected $validate;

    public function __construct()
    {
        parent::__construct();

        $this->model = new ReservationSeat();
        $this->validate = new ReservationValidate();
    }

    /**
     * 获取排版信息
     * @param reservation_id  座位预约id
     */
    public function scheduleList()
    {
        $scheduleModel = new ReservationSchedule();
        $res = $scheduleModel->lists($this->request->reservation_id);
        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 根据状态获取格子列表 (只能用于 node 为 7 的情况)
     * @param reservation_id  预约id
     * @param make_status   1 空闲  2 预约待领取  3 使用中
     */
    public function geSeatListBytStatus()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('get_seat_list_by_status')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        $res = $this->model->geSeatListBytStatus($this->request->reservation_id, $this->request->make_status);
        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 座位预览
     * @param reservation_id  座位预约id
     * @param schedule_id     排版id
     * @param schedule_type     排版类型
     * @param make_time     预约时间
     * @param page int 当前页数
     * @param limit int 分页大小
     */
    public function lists()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('seat_list')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? $this->request->limit : 10;
        $schedule_type = $this->request->schedule_type ? $this->request->schedule_type : 1;

        $res = $this->model->lists($this->request->reservation_id, $this->request->schedule_id, $schedule_type, $this->request->make_time, null, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        $res = $this->disPageData($res);
        $res['data'] = $this->addSerialNumber($res['data'], $page, $limit);

        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 新增座位
     * @param reservation_id  座位预约id
     * @param number 新增个数
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('seat_add')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        $reservationInfo = Reservation::where('id', $this->request->reservation_id)->first();
        if (empty($reservationInfo)) {
            return $this->returnApi(201, "参数传递错误");
        }

        DB::beginTransaction();
        try {
            //dump([$this->request->reservation_id, $reservationInfo->number + $this->request->number, $reservationInfo->number]);die;
            $new_number = $this->model->change($this->request->reservation_id, $this->request->number, $reservationInfo->number);

            //修改作为个数
            $reservationInfo->number = $reservationInfo->number + $new_number;
            $reservationInfo->save();

            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 座位发布与撤销
     * @param ids 书籍id，多个用逗号拼接   all 是全部
     * @param is_play 是否发布  1.发布  2.撤销  默认2
     */
    public function playAndCancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('seat_play_and_cancel')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        DB::beginTransaction();
        $is_play = $this->request->is_play == 1 ? '启用' : '撤销';
        try {

            $this->model->resumeAndCancel($this->request->ids, 'is_play', $this->request->is_play);

            //撤销已取消的座位的预约
            if ($this->request->is_play == 2) {

                $applyModel = new ReservationApply();

                if ($this->request->ids == 'all') {
                    $seat_id = null;
                } else {
                    $seat_id = explode(',', $this->request->ids);
                }

                $applyInfo = $applyModel->getApplyInfo(null, $seat_id, date('Y-m-d'), '>', [1, 3]);
                if ($applyInfo) {
                    $apply_ids = array_column($applyInfo, 'id');
                    $applyModel->whereIn('id', $apply_ids)->update(['status' => 2, 'change_time' => date('Y-m-d H:i:s')]);
                    $reservation_name = Reservation::where('id', $applyInfo[0]['reservation_id'])->value('name');
                    foreach ($applyInfo as $key => $val) {
                        $this->systemAdd("读者预约：申请失效", $val['user_id'], $val['account_id'], 34, intval($val['id']), '您申请的预约：【' . $reservation_name . '】当前座位已被管理员撤销,您的预约已失效,请重新预约');
                    }
                }
            }
            DB::commit();
            return $this->returnApi(200, $is_play . "成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 删除座位
     * @param seat_ids 座位id  多个逗号拼接  删除必须从最大的开始删除
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('seat_del')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $seat_ids = explode(',', $this->request->seat_ids);
        $seat_info = $this->model->where('id', $seat_ids[0])->first();

        if (empty($seat_info)) {
            return $this->returnApi(201, "参数传递错误");
        }
        $reservation_id = $seat_info['reservation_id'];

        //判断是否包含最大的数据
        $count = count($seat_ids);
        $seat_info_id = $this->model->where('reservation_id', $reservation_id)->where('is_del', 1)->orderByDesc('id')->limit($count)->pluck('id')->toArray();

        if (count(array_intersect($seat_info_id, $seat_ids)) != $count) {
            return $this->returnApi(201, "删除座位必须从最后的座位开始删除");
        }

        DB::beginTransaction();
        try {
            $number = $this->model->whereIn('id', $seat_ids)->where('is_del', 1)->update(['is_del' => 2, 'change_time' => date('Y-m-d H:i:s')]);
            Reservation::where('id', $reservation_id)->decrement('number', $number);
            //撤销已取消的座位的预约
            $applyModel = new ReservationApply();

            $reservation_info = Reservation::select('name', 'node')->where('id', $reservation_id)->first();
            $applyInfo = $applyModel->getApplyInfo(null, [$this->request->seat_ids], date('Y-m-d'), '>', [1, 3], null, null, $reservation_info['node']);
            if ($applyInfo) {
                $apply_ids = array_column($applyInfo, 'id');
                $applyModel->whereIn('id', $apply_ids)->update(['status' => 2, 'change_time' => date('Y-m-d H:i:s')]);
                $reservation_name = $reservation_info['name'];
                foreach ($applyInfo as $key => $val) {
                    $this->systemAdd("读者预约：申请失效", $val['user_id'], $val['account_id'], 34, intval($val['id']), '您申请的预约：【' . $reservation_name . '】当前座位已被管理员删除,您的预约已失效,请重新预约');
                }
            }

            DB::commit();
            return $this->returnApi(200, "删除成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }

    /**
     * 下载座位二维码
     * @param reservation_id  座位预约id
     */
    public function downloadQr()
    {

        //增加验证场景进行验证
        if (!$this->validate->scene('download_qr')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }
        $id = $this->request->reservation_id;
        $seat_list = $this->model->seatList($id);
        $reservation_info = Reservation::select('name', 'serial_prefix')->where('id', $id)->where('is_del', 1)->first();
        if (empty($reservation_info)) {
            return $this->returnApi(203, "预约不存在");
        }

        $zipFileDownloadObj = new ZipFileDownloadController();
        $path_arr = [];
        $end_seat = end($seat_list);
        $end_seat = strlen($end_seat['number']);
        foreach ($seat_list as $key => $val) {
            $path_arr[$key]['file_path'] = $val['qr_url'];
            $path_arr[$key]['file_name'] = $this->model->getSeatNumber($reservation_info->serial_prefix, $end_seat, $val['number']) . '.png';
        }
        //        return $path_arr;
        $file_name = $reservation_info->name;
        $zip_path = $zipFileDownloadObj->addPackage($path_arr, null, $file_name . '-二维码下载-' . date('Y-m-d'), 10); //缓存时间长了，筛选数据还是之前的

        return response()->download($zip_path);
    }
}
